package uk.co.hs.web.security.filter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import uk.co.hs.constants.SecurityConstants;
import uk.co.hs.service.admin.interfaces.WebUserServiceInterface;

public class AdminAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler
{
  @Autowired(required=true)
  @Qualifier("hs_webUserService")
  private WebUserServiceInterface mUserService;

	/**
	 * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler
	 * #onAuthenticationFailure(javax.servlet.http.HttpServletRequest,
	 *                          javax.servlet.http.HttpServletResponse,
	 *                          org.springframework.security.core.AuthenticationException)
	 * {@inheritDoc}
	 */
  public void onAuthenticationFailure(HttpServletRequest aRequest,
			                                HttpServletResponse aResponse,
			                                AuthenticationException aAuth) throws IOException, ServletException
	{
		String userName = aRequest.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
		String result = mUserService.incrementFailedLoginAttempts(userName);
		if (result.equals(SecurityConstants.LOCKED))
		{
			mUserService.lockUser(userName);
			setDefaultFailureUrl("/accountLocked.htm");
		}
		else if (result.equals(SecurityConstants.EXPIRED))
		{
			setDefaultFailureUrl("/expiredPassword.htm?user=" + userName);
		}
		else
		{
			setDefaultFailureUrl("/login.htm?error=true&fail=" + result);
		}
		super.onAuthenticationFailure(aRequest, aResponse, aAuth);
	}


}
